<template>
    <div class="contentBody">
        <!-- 头部区域开始 -->
        <header class="nav">
            <div class="header-content">
                <!--logo-->
                <div class="header-logo">
                    <img src="@/assets/imge/logo.png" alt="" :width="210" :height="60">
                </div>
                <!-- 预留位 -->
                <div >

                </div>
                <!-- 草稿箱 -->
<!--                <el-button class="with-padding">草稿箱</el-button>-->
                <!-- 发布设置 -->
                <div class="publish-popup with-padding">
                    <el-button type="primary" class="xitu-btn" @click="handleOpen"> 发布 </el-button>
                    <!--发文设置-->
                    <el-dialog class="panel" v-model="isOpen" width="650px" destroy-on-close>
                        <el-form :rules="data.rules">
                            <span style="font-size: 22px; padding: 0 520px 10px 5px; border-bottom: 2px #f5f4f1 solid">发布博客</span>
                            <!-- 分类 -->
                            <el-form-item property="category" label="分类:(必选)">
                                <div class="category-tag">
                                    <el-tag
                                        v-for="(category, index) in categories"
                                        :key="index"
                                        :class="{ active: selectedCategory === category.categoryId }"
                                        @click="selectedCategory = category.categoryId"
                                    >
                                        {{ category.categoryName }}
                                    </el-tag>
                                </div>
                            </el-form-item>
                            <!-- 标签 -->
                            <el-form-item label="标签:(可选)">
                                <!-- 搜索添加标签 -->
                                <div>
                                    <el-select
                                        v-model="tagsValue"
                                        multiple
                                        filterable
                                        remote
                                        reserve-keyword
                                        placeholder="请搜索添加标签..."
                                        remote-show-suffix
                                        :remote-method="remoteMethod"
                                        :loading="loading"
                                        style="width: 440px"
                                    >
                                        <el-option
                                            v-for="item in options"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </div>
                            </el-form-item>
                            <!-- 内容封面 -->
                            <el-form-item label="内容封面:(可选)">
                                <!--上传缓存图片-->
                                <div>
                                    <el-upload
                                        ref="cover"
                                        :action = "`http://localhost:8000/api/uploadImage`"
                                        :file-list="coverFileList"
                                        :on-success="handleUploadSuccess"
                                        list-type="picture-card"
                                        :limit="1"
                                        accept="image/jpeg,image/png"
                                    ><!-- 自动上传:auto-upload="false" -->
                                        <el-icon><Plus /></el-icon>
                                        <span>上传封面</span>
                                        <template #file="{ file }">
                                            <div>
                                                <img class="el-upload-list__item-thumbnail" style="object-fit: contain" :src="file.url" alt="" />
                                                <span class="el-upload-list__item-actions">
                                                      <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                                        <el-icon><Delete /></el-icon>
                                                      </span>
                                                </span>
                                            </div>
                                        </template>
                                    </el-upload>
                                </div>
                            </el-form-item>
                            <!-- 按钮 -->
                            <el-form-item style="position: relative; height: 30px">
                                <template #default >
                                    <div style="position: absolute; right: 10px; display: flex; gap: 20px">
                                        <el-button @click="isOpen = false">取消</el-button>
                                        <el-button type="primary" @click="publishBolg">确认并发布</el-button>
                                    </div>
                                </template>
                            </el-form-item>
                        </el-form>
                    </el-dialog>
                </div>
            </div>
        </header>
        <!-- 头部区域结束 -->
        <!--  下方区域开始 -->
        <div class="contentArea">
            <!-- 编辑器功能区 -->
            <div style="position: fixed; top: 80px; z-index: 100">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="data.mode"
                />
            </div>
            <!-- 标题 -->
            <textarea v-model="title" placeholder="输入标题..." spellcheck="false" maxlength="80" rows="1" class="title-input" style="height: 170px;"></textarea>
            <!-- 正文内容 -->
            <Editor class="rich-text-editor-content"
                style="overflow-y: hidden"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="data.mode"
                @onCreated="handleCreated"
                @onChange="handleEditorChange"
            />
        </div>
        <!-- 下方区域结束 -->
    </div>
</template>

<script setup>
import {ref, reactive, shallowRef, onBeforeUnmount, onMounted} from 'vue'
import {Delete, Plus} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import router from "@/router/index.js";


//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}


// 表单数据
const title = ref('');  // 标题数据
const cover = ref();  // 封面路径
const data = reactive({
    mode: 'simple',
})

// 发布设置控制
const isOpen = ref(false);
// 发布设置页置空
const handleOpen = () => {
    isOpen.value = true;
    selectedCategory.value = ''
    tagsValue.value = []
    coverFileList.value = []
}
const disabled = ref(false);  // 状态管理
const coverFileList = ref([])  // 文件上传列表
const handleRemove = (file) => {
    // 从文件列表中移除指定文件
    coverFileList.value = coverFileList.value.filter((f) => f.uid !== file.uid);
};
const handleUploadSuccess = (response) => {
    console.log(response)
    if (response && response.errno === 0 && response.data && response.data.url) {
        cover.value = response.data.url
    } else {
        ElMessage.error(response.msg)
    }
};
// 分类数据
const categories = ref([]);  // 保存所有的分类数据
const selectedCategory = ref('');  // 选择分类数据

// 标签数据
// 初始化状态
const list = ref([])  // 所有的标签列表
const options = ref([])  // 搜索到的标签选项
const tagsValue = ref([])  // 选择的标签数据
const loading = ref(false) // 加载状态控制

// 远程搜索方法
const remoteMethod = (query) => {
    if (!query) {
        options.value = []
        return
    }
    loading.value = true
    // 发起API请求
    request.get('/api/cata/selectTagAll').then(res => {
        loading.value = false
        if (res.code === '200' && res.data && res.data.length > 0) {
            // 转换响应数据格式，提取tagName字段
            list.value = res.data.map(tag => ({
                value: tag.tagName,
                label: tag.tagName  // 使用tagName作为标签显示
            }))
            // 本地过滤标签
            options.value = list.value.filter(item =>
                item.label.toLowerCase().includes(query.toLowerCase())
            )
        } else {
            options.value = []
            ElMessage.error("未找到匹配的标签")
        }
    }).catch(error => {
        loading.value = false
        ElMessage.error("获取标签失败")
        console.error(error)
    })
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p></p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p></p>'
    }, 1500)
// 获取分类列表
    request.get('/api/cata/selectCateAll').then(res => {
        if (res.code === '200') {
            categories.value = res.data; // 缓存新数据
        } else {
            console.log("分类列表查询失败")
        }
    })
})

const toolbarConfig = {

}   // 工具栏配置

const editorConfig = {
    placeholder: '请输入内容...' ,
    MENU_CONF: {},   // 初始化 MENU_CONF 属性
}   // 编辑器配置
// 修改 uploadImage 菜单配置
editorConfig.MENU_CONF['uploadImage'] = {
    server: 'http://localhost:8000/api/uploadImage',  // 上传图片的服务器地址
    fieldName: 'file',  // 指定上传参数名，与后端接口一致
    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 1024 * 1024, // 1M
    // 最多可上传几个文件，默认为 100
    maxNumberOfFiles: 100,
    // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['image/*'],
    onBeforeUpload(file) {
        // file 选中的文件，格式如 { key: file }
        return file
    },
    // 自定义上传成功的回调函数，确保正确处理返回结果
    // 上传成功的回调
    onSuccess(files, result) {
        console.log('上传成功，后端返回:', result);
        // 检查后端返回格式是否正确
        if (result && result.errno === 0 && result.data && result.data.url) {
            // 正确格式：{ errno: 0, data: { url: "图片URL" } }
            return {
                errno: 0, // 必须返回0表示成功
                data: {
                    urls: [result.data.url] // 提取真正的图片URL
                }
            };
        } else {
            // 处理非预期格式
            console.error('后端返回格式异常:', result);
            return {
                errno: 1,
                message: '上传成功但返回格式错误'
            };
        }
    },

    // 自定义上传失败的回调函数
    onFailed(err, files, result) {
        console.log('上传的文件:', files);
        console.log('后端返回结果:', result);
        console.error('图片上传出错:', err);
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const handleEditorChange = () => {
    const editorElement = document.querySelector('.rich-text-editor-content');
    if (editorElement) {
        editorElement.scrollTop = editorElement.scrollHeight;
    }
}

// 发布博客事件方法
const publishBolg = () => {
    console.log(tagsValue.value)
// 整理标签名称为逗号分隔的字符串（如"前端技术,后端开发"）
    const tagNames = tagsValue.value.map(tag => tag.tagName).join(',');
    const coverValue = coverFileList.value.length !== 0 ? cover.value : null
    console.log()
    const formData = {
        userId: user.user_id,  // 创建博客的用户id
        title: title.value,   // 博客标题
        cover: coverValue, // 博客封面
        content: valueHtml.value,    // 博客正文
        contentType: 'BOLG',  // 内容类型
        categoryId: selectedCategory.value,  // 分类
        tags: tagNames,
    }
    console.log(formData)
    submitData(formData);  // 提交数据都后端
}

// 提交数据到后端
const submitData = (formData) => {
    try {
        request.post('/api/content/addContent', formData).then(res => {
            if (res.code === '200') {
                ElMessage.success("发布成功")
                router.push('/bolg')
            } else if (res.code === '500') {
                ElMessage.error(res.msg)
            } else {
                ElMessage.error('博客发布失败')
            }
        })
    } catch (error) {
        ElMessage.error('网络错误:', error)
    }
}
</script>

<style scoped>
.contentBody {
    min-height: 87vh;
    margin: 0 auto;
    display: flex;
}
/*整体内容区域样式*/
.contentArea {
    display: flex;
    position: relative;
    background-color: #fff;
    width: 100%;
    margin: 0 auto;
    align-items: center;
    justify-content: center;
    overflow: auto;
    top: 80px;
    flex-direction: column;
}
.nav {
    display: flex;
    position: fixed;
    width: 100%;
    align-items: center;
    justify-content: center;
    top: 0;
    background-size: 4px 4px;
    z-index: 999;
    padding: 0 1.4rem;
    height: 5.0rem;
    background-color: #fff;
    border-bottom: none;
}
.header-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    width: 83.334rem;
    max-width: 100%;
    height: 100%;
}
.header-logo {
    position: relative;
    margin: 0 auto 0 120px;
    width: 180px;
    height: 60px;
}
.header-content .publish-popup {
    min-width: 91px;
    margin-right: 110px;
}
.with-padding {
    padding: 0 1.2rem;
}
.xitu-btn {
    height: 32px;
    padding: 2px 16px;
    font-size: 14px;
    line-height: 22px;
    border: 1px solid #1d7dfa;
    border-radius: 2px;
    cursor: pointer;
    color: #fff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    background-color: #1d7dfa;
}
.panel {
    height: 32px;
    padding: 2px 16px;
    font-size: 14px;
    line-height: 22px;
    border: 1px solid #1d7dfa;
    border-radius: 2px;
    cursor: pointer;
    color: #fff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    background-color: #1d7dfa;
}
.panel .el-form-item {
    display: flex;
    margin: 20px 20px 32px;
}
.el-upload-list__item-thumbnail {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.category-tag {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 10px 0;
}
.category-tag .el-tag {
    padding: 5px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    height: 30px;
    font-size: 14px;
}
.category-tag .el-tag.active {
    color: #fffefb;
    background-color: #1677ff;
}

.contentArea .title-input {
    padding-top: 5.666rem;
    padding-left: calc(50% - 32.834rem);
    width: 100%;
    -webkit-box-flex: 0;
    flex: none;
    position: relative;
}

.title-input {
    margin: 0;
    padding: 0;
    font-size: 2.000rem;
    font-weight: 700;
    color: #000;
    border: none;
    outline: none;
    resize: none;
    overflow: hidden;
    word-break: break-word;
}

.contentArea .rich-text-editor-content {
    -webkit-box-flex: 1;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    position: relative;
    padding-left: calc(50% - 33.000rem);
    outline: none;
    overflow: hidden;
}
.rich-text-editor-content {
    font-size: 16px;
    width: 100%;
    line-height: 1.6;
    word-break: break-word;
}
</style>